<?php
namespace app\store\controller;

use think\Config;
use addons\wxsaas\library\Wechat;
use app\store\model\Applet as AppletModel;
use app\store\model\AppletToken as AppletTokenModel;

/**
 * 授权回调
 */
class Auth extends \think\Controller
{
	/**
     * 应用授权
     */
    public function wechat($applet_id)
    {
        $auth_code = empty ( $_GET ['auth_code'] ) ?"" : trim ( $_GET ['auth_code'] );  //获取授权码
        if(!empty($auth_code)){
            $wx = new Wechat;
            //获取授权信息
            $result = $wx->getAuth($auth_code);
            $auth = $result['authorization_info'];//得到授权信息
            //获取授权应用的帐号基本信息
            $result = $wx->getAppInfo($auth['authorizer_appid']);
            $app = $result['authorizer_info'];//得到授权应用的帐号基本信息
            
            $api_domain = '';
            $signature = '';
            $wxapp = AppletModel::get($applet_id);
            if($wxapp['app_type']==10){
                //添加服务器域名
                $serveDomain = $wx->setServeDomain(0,'',$auth['authorizer_access_token']);
                if($serveDomain['errcode'] == 0){
                    $api_domain = $serveDomain['apiurl'];
                }
                //设置小程序简介
                $setSignature = $wx->setSignature(0,'',$auth['authorizer_access_token']);
                if($setSignature['errcode'] == 0){
                    $signature = $setSignature['signature'];
                }
            }
            $wxapp->save([
                'app_id' => $auth['authorizer_appid'],//授权方APPid
                'user_name' => $app['user_name'],//原始ID
                'app_name' => isset($app['nick_name'])?$app['nick_name']:'',    //昵称
                'head_img' => isset($app['head_img'])?$app['head_img']:'',//头像
                'qrcode_url' =>$app['qrcode_url'],  //二维码地址
                'principal_name' => $app['principal_name'], //主体名称  
                'api_domain' => $api_domain, 
                'signature' => $signature, 
                'status' => 1   
            ]);
            if(!$token = AppletTokenModel::where('applet_id',$applet_id)->find()){
                $token = new AppletTokenModel;
            }
            $token->save([
            	'token_type' => 10,
                'applet_id' => $applet_id,
                'access_token' => $auth['authorizer_access_token'], //令牌
                'expires_in' => time()+3600,//令牌过期时间
                'authorizer_refresh_token' => $auth['authorizer_refresh_token'],//刷新令牌         
            ]);
            if($wxapp['app_type']==10){
                $this->redirect(url('wxsaas.wxapp/index'));
            }
            $this->redirect(url('wxsaas.wechat/index'));
        }
    }
	
}
